package com.example.xinhuazidian

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.xinhuazidian.utils.JsonFileUtil
import com.example.xinhuazidian.adapter.ShuimmotangshiAdapter
import com.example.xinhuazidian.bean.Shuimotangshi
import com.example.xinhuazidian.databinding.ActivityShuimotangshiBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import java.lang.reflect.Type

/**
 * 水墨唐诗
 */
class ShuimotangshiActivity : AppCompatActivity(),
    ShuimmotangshiAdapter.OnRecyclerItemClickListener {

    private lateinit var binding: ActivityShuimotangshiBinding
    private var shuimmotangshiAdapter: ShuimmotangshiAdapter? = null
    private var str: String? = null
    private lateinit var mapBeanList: MutableList<Shuimotangshi>
    private var fileName: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityShuimotangshiBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initView()
        initData()
    }

    private fun initView() {
        //沉浸状态栏
        ImmersionBar.with(this)
            .statusBarDarkFont(true)//状态栏字体是深色，不写默认为亮色
            .init()

        fileName = intent.getStringExtra("fileName")
        if (fileName != null) {
            load(fileName!!)
        }
    }

    private fun initData() {
        shuimmotangshiAdapter?.setRecyclerItemClickListener(this)
    }

    @SuppressLint("SetTextI18n")
    private fun load(fileName: String) {
        str = JsonFileUtil.loadFile(this, fileName)

        val mapBeanListType: Type = object : TypeToken<ArrayList<Shuimotangshi?>?>() {}.type
        mapBeanList = Gson().fromJson(str, mapBeanListType)
        initAdapter(mapBeanList)

        binding.tvNum.text = "一共${mapBeanList.size}首"
    }

    private fun initAdapter(list: MutableList<Shuimotangshi>) {
        val staggeredGridLayoutManager =
            StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL)
        binding.rv.layoutManager = staggeredGridLayoutManager

        //加载适配器
        shuimmotangshiAdapter = ShuimmotangshiAdapter(list)
        binding.rv.adapter = shuimmotangshiAdapter
    }

    override fun onRecyclerItemClick(position: Int) {
        intent = Intent(this, ShuimotangshiXiangqingActivity::class.java)
        intent.putExtra("bean", Gson().toJson(mapBeanList[position]))
        startActivity(intent)
    }
}